package com.cy.ppj.service.account.impl;

import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.dao.mapper.user.UserInfoMapper;
import com.cy.ppj.dao.mapper.user.UserMapper;
import com.cy.ppj.dao.mapper.user.UserRecommenderMapper;
import com.cy.ppj.model.domian.user.User;
import com.cy.ppj.model.domian.user.UserInfo;
import com.cy.ppj.model.domian.user.UserRecommender;
import com.cy.ppj.model.dto.recommender.UserRecommenderDTO;
import com.cy.ppj.model.enums.account.BrokerLevel;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.account.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @description: 用户信息
 * @author: Ocean
 * @create: 2018-09-11 10:12
 **/
@Slf4j
@Service
public class UserInfoServiceImpl extends BaseService implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserRecommenderMapper userRecommenderMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public BrokerLevel queryBrokerLevel(Long userId) {
        return userInfoMapper.queryLevelByUserId(userId);
    }

    @Override
    public UserInfo queryUserInfo(UserInfo userInfo) {
        return userInfoMapper.selectOne(userInfo);
    }

    @Override
    public int queryUserInfoCount(UserInfo userInfo) {
        return userInfoMapper.selectCount(userInfo);
    }

    @Override
    @Transactional
    public void insertUserInfo(UserInfo userInfo) {

        Date time = new Date();

        UserInfo dbUserInfo = new UserInfo();
        dbUserInfo.setUserId(userInfo.getUserId());
        dbUserInfo = userInfoMapper.selectOne(dbUserInfo);

        if (dbUserInfo != null) {
            UserInfo temp = new UserInfo();
            temp.setId(dbUserInfo.getId());
            temp.setBankNo(userInfo.getBankNo());
            temp.setBankCard(userInfo.getBankCard());
            temp.setBankMobile(userInfo.getBankMobile());
            temp.setUpdateTime(time);
            userInfoMapper.updateByPrimaryKeySelective(temp);
            return;
        }

        if (userInfo.getCreateTime() != null) {
            time = userInfo.getCreateTime();
        }
        userInfo.setSex(CommonUtils.getSexByIdNo(userInfo.getIdNo()));
        userInfo.setNewUser(true);
        //实名认证，成为白银小精灵
        userInfo.setLevel(BrokerLevel.OFFICIAL);
        userInfo.setUpgradeTime(time);
        userInfo.setCreateTime(time);
        userInfo.setUpdateTime(time);
        userInfoMapper.insertSelective(userInfo);

        //实名成功之后，更新实名状态
        User user = new User();
        user.setId(userInfo.getUserId());
        user.setRealAuth(true);
        user.setUpdateTime(time);
        userMapper.updateByPrimaryKeySelective(user);

        Long userId = userInfo.getUserId();
        //找到当前实名用户的上级用户
        UserRecommenderDTO firstUserRecommenderDTO = userRecommenderMapper.selectUserRecommenderByUserId(userId);
        if(firstUserRecommenderDTO != null) {
            if(BrokerLevel.OFFICIAL.equals(firstUserRecommenderDTO.getLevel())) {
                //如果当前用户的上级用户是白银小精灵，则判断其下级用户有几个白银小精灵
                int officialCount = userRecommenderMapper.selectCountByRecommendUserIdAndLevel(firstUserRecommenderDTO.getRecommendUserId(), BrokerLevel.OFFICIAL);
                if(officialCount >= 5) {
                    //如果超过5个白银，则升级为黄金
                    UserInfo firstRecommendUserInfo = new UserInfo();
                    firstRecommendUserInfo.setId(firstUserRecommenderDTO.getRecommendUserInfoId());
                    firstRecommendUserInfo.setLevel(BrokerLevel.GOLDEN);
                    firstRecommendUserInfo.setUpdateTime(time);
                    userInfoMapper.updateByPrimaryKeySelective(firstRecommendUserInfo);

                    //上级用户升级为黄金之后，再判断上级的上级是否满足升钻石
                    UserRecommenderDTO secondUserRecommenderDTO = userRecommenderMapper.selectUserRecommenderByUserId(firstUserRecommenderDTO.getRecommendUserId());
                    if(secondUserRecommenderDTO != null) {
                        if(BrokerLevel.GOLDEN.equals(secondUserRecommenderDTO.getLevel())) {
                            //如果上级的上级用户是黄金小精灵，则判断其下级用户有几个黄金小精灵
                            int goldenCount = userRecommenderMapper.selectCountByRecommendUserIdAndLevel(secondUserRecommenderDTO.getRecommendUserId(), BrokerLevel.GOLDEN);
                            if(goldenCount >= 5) {
                                //如果超过5个黄金，则升级为钻石
                                UserInfo secondRecommendUserInfo = new UserInfo();
                                secondRecommendUserInfo.setId(secondUserRecommenderDTO.getRecommendUserInfoId());
                                secondRecommendUserInfo.setLevel(BrokerLevel.DIAMOND);
                                secondRecommendUserInfo.setUpdateTime(time);
                                userInfoMapper.updateByPrimaryKeySelective(secondRecommendUserInfo);
                            }
                        }
                    }
                }
            }
        }




    }

	@Override
	@Transactional
	public void updateNewUserToFalse() {
		List<UserInfo> userInfoList = userInfoMapper.selectNewUserList();
		List<Long> userIds = new ArrayList<>();
		userInfoList.stream().forEach(u -> {
			// 当前时间
			Date now = new Date();
			// 体验期到期时间
			Date experienceTime = CommonUtils.addTime(u.getCreateTime(), 3, Calendar.MONTH);
			if(now.getTime() - experienceTime.getTime() >= 0) {
				// 如果当前时间 now 比体验期到期时间 experienceTime 大于或等于，则更新用户为旧用户
				userIds.add(u.getUserId());
			}
		});
		
		// 批量更新
		if(!CommonUtils.isEmpty(userIds)) {
			userInfoMapper.updateNewUserToFalse(userIds);
		}
		
	}

    @Override
    @Transactional
    public void batchUpdateUserInfoToGolden() {
        Date time = new Date();
        UserInfo dbUserInfo = new UserInfo();
        dbUserInfo.setLevel(BrokerLevel.OFFICIAL);
        List<UserInfo> list = userInfoMapper.select(dbUserInfo);
        for(UserInfo userInfo : list) {
            int officialCount = userRecommenderMapper.selectCountByRecommendUserIdAndLevel(userInfo.getUserId(), BrokerLevel.OFFICIAL);
            if(officialCount >= 5) {
                //升级为黄金
                userInfo.setLevel(BrokerLevel.GOLDEN);
                userInfo.setUpdateTime(time);
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
            }
        }
    }

    @Override
    @Transactional
    public void batchUpdateUserInfoToDiamond() {
        Date time = new Date();
        UserInfo dbUserInfo = new UserInfo();
        dbUserInfo.setLevel(BrokerLevel.GOLDEN);
        List<UserInfo> list = userInfoMapper.select(dbUserInfo);
        for(UserInfo userInfo : list) {
            int goldenCount = userRecommenderMapper.selectCountByRecommendUserIdAndLevel(userInfo.getUserId(), BrokerLevel.GOLDEN);
            if(goldenCount >= 5) {
                //升级为黄金
                userInfo.setLevel(BrokerLevel.DIAMOND);
                userInfo.setUpdateTime(time);
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
            }
        }
    }
}
